package info.webest.media.image;

import java.util.ArrayList;

import info.webest.media.R;
import info.webest.media.files.FileManager;
import info.webest.media.files.FileManager.ContentType;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

public class GalleryViewerActivity extends Activity {

	private String folder;
	private ArrayList<String> images;
	private Bitmap bmp = null;

	ImageView iv;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.gallery);
		
		iv = (ImageView) findViewById(R.id.imageView);
		

		Intent intent = getIntent();
		if (intent != null) {
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				folder = bundle.getString("Folder");
			}
		}

		Gallery ga = (Gallery) findViewById(R.id.gallery);
		ga.setAdapter(new ImageAdapter(this, folder));
		ga.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				bmp = BitmapFactory.decodeFile(images.get(arg2));
				iv.setImageBitmap(bmp);
			}
		});

	}

	public class ImageAdapter extends BaseAdapter {

		private Context ctx;
		int imageBackground;

		public ImageAdapter(Context c, String folder) {
			ctx = c;
			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
			imageBackground = ta.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 1);
			ta.recycle();
			
			images = FileManager.getFileList(folder, ContentType.IMAGE);
		}

		@Override
		public int getCount() {

			return images.size();
		}

		@Override
		public Object getItem(int arg0) {

			return arg0;
		}

		@Override
		public long getItemId(int arg0) {

			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {

			ImageView iv = new ImageView(ctx);
			bmp = BitmapFactory.decodeFile(images.get(arg0));
			iv.setImageBitmap(bmp);

			iv.setScaleType(ImageView.ScaleType.FIT_XY);
			iv.setLayoutParams(new Gallery.LayoutParams(150, 120));
			iv.setBackgroundResource(imageBackground);
			return iv;
		}

	}
}